//专门用来输出关于localStorage的存取数据的方法

export const KEY = "shoppingData"

//获取数据
export function getItem() {
    return JSON.parse(localStorage.getItem(KEY) || '[]');
}

//存储数据
export function setItem(item) {
    var shopinfo = getItem();
    shopinfo.push(item);
    localStorage.setItem(KEY, JSON.stringify(shopinfo));
}

//删除数据
export function delItem(id) {
    var arr = getItem();
    for (var i = arr.length - 1; i >= 0; i--) {
        if (arr[i].goodsId == id) {
            arr.splice(i, 1)
        }
    }
     localStorage.setItem(KEY, JSON.stringify(arr));
}

//更新数据
export function updateData(obj) {
    var arr = getItem();
    if (obj.type == "add") {
        arr.push({
            goodsId: obj.id,
            goodsCount: 1
        })
    } else {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].goodsId == obj.id) {
                if (arr[i].goodsCount > 1) {
                    arr[i].goodsCount--;
                    break;
                } else {
                    arr.splice(i, 1);
                    break;
                }
            }
        }
    }
    localStorage.setItem(KEY, JSON.stringify(arr));
}